<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="标题">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="信息来源">
        <el-select
          v-model="formData.classify"
          placeholder="请选择信息来源"
          filterable
        >
          <el-option
            v-for="(item, index) in classifyOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <div class="classIfy-tips">
          没找到信息来源，试试
          <add-class-dialog @update="getClassiyOptions" />
          信息来源
        </div>
      </el-form-item>
      <el-form-item label="封面">
        <div class="upload-container">
          <input
            type="file"
            ref="uploadInput"
            style="display: none"
            @change="handleFileChange"
            accept="image/*"
          />
          <el-button @click="chooseFile">选择图片</el-button>
          <img
            v-if="formData.bg"
            :src="formData.bg"
            alt="封面图片"
            style="max-width: 150px; max-height: 150px; margin-top: 10px"
          />
        </div>
      </el-form-item>
      <el-form-item label="发表时间">
        <el-date-picker
          v-model="formData.publishTime"
          type="datetime"
          placeholder="选择日期时间"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="内容">
        <RichTextEditor ref="myWangEditor" v-model="formData.detail" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="previewContent">预览</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import RichTextEditor from "@/components/RichTextEditor";
import addClassDialog from "./components/add-classIfy-dialog";

export default {
  name: "EditArticle", // 将组件名改为多单词形式

  components: {
    RichTextEditor,
    addClassDialog,
  },
  data() {
    return {
      formData: {
        title: "",
        classify: "",
        publishTime: new Date(),
        detail: "",
      },
      classifyOptions: [],
    };
  },
  mounted() {
    this.init();
    this.getClassiyOptions();
  },
  methods: {
    async init() {
      const { type, id } = this.$route.query;

      if (type === "edit") {
        const data = await this.getArticleInfo(id);
        console.log("data", data);

        this.$nextTick(() => {
          this.formData = { ...data };
          this.$refs.myWangEditor.setHtml(data.detail);
        });
      }
    },

    chooseFile() {
      this.$refs.uploadInput.click(); // 触发文件选择框
    },

    async getClassiyOptions() {
      const { data } = await this.$fetch.get("/api/article/classIfy/list", {});
      this.classifyOptions = data.map((item) => ({
        ...item,
        label: item.value,
      }));
    },

    handleFileChange(event) {
      const file = event.target.files[0];

      if (file && /\.(jpg|jpeg|png|gif)$/i.test(file.name)) {
        this.readFile(file);
      } else {
        this.$message.error("请仅选择图片文件");
      }
    },
    uploadFile(file) {
      this.formData.bg = URL.createObjectURL(file); // 显示预览图
      const formData = new FormData();
      formData.append("file", file);

      // 假设使用axios进行上传
      // axios.post('/api/custom-upload', formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data',
      //   },
      // }).then((response) => {
      //   console.log('上传成功', response);
      //   // 假设服务器返回了图片URL
      //   if (response.data.url) {
      //     this.formData.coverUrl = response.data.url;
      //     this.imageUrl = response.data.url; // 更新预览图
      //   }
      // }).catch((error) => {
      //   console.error('上传失败', error);
      // });
    },

    async getArticleInfo(id) {
      const { data } = await this.$fetch.get(`/api/article/${id}`);
      return data || {};
    },

    async submitForm() {
      const url =
        this.$route.query.type === "add"
          ? "/api/article/create"
          : "/api/article/update";
      const detail = this.$refs.myWangEditor.getHtml();
      const { code } = await this.$fetch.post(url, {
        ...this.formData,
        detail,
      });
      if (code === 0) {
        this.$message.success("成功");
        this.$router.push({
          path: "/content/article",
        });
      }
    },
    previewContent() {
      const detail = this.$refs.myWangEditor.getEditor().getText();
      console.log(`预览内容：\n${detail}`);
    },
  },
};
</script>

<style scoped>
#editor {
  width: 100%;
  height: 300px;
}

.classIfy-tips {
  color: #999;
  position: absolute;
  left: 224px;
  top: 0;
  display: flex;
}
</style>
